<?php
/**
 * 公司基本信息模型
 */

namespace app\admin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use map\BaiDu;
use oss\Oss;
use think\Db;
use think\Exception;

class Company extends BaseModel {

    /**
     * 添加公司基本信息
     * @param $params
     * @return bool
     * @throws Exception
     */
    public static function post($params) {
        if (!empty($params['id'])) {
            $old = db("company")->where('id', $params['id'])->where('deleted', 0)->find();
            if (empty($old)) {
                Err::add('数据不存在', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (preg_match("/^([\x{4e00}-\x{9fa5}]|\w){1,15}$/u", trim($params['f_name'])) == false) {
            Err::add('法人名字：15长度，数字、字母、汉字、下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if (mb_strlen(trim($params['address'],'utf-8'))>30) {
            Err::add('地址：30长度', RespCode::PARAMS_ERR);
            return false;
        }
        if (empty($params['id'])) {
            if (!preg_match('/^1[3-9]\d{9}$/', trim($params['f_phone']))) {
                Err::add('法人电话号码不正确', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (preg_match("/^([\x{4e00}-\x{9fa5}]|\w){1,50}$/u", trim($params['name'])) == false) {
            Err::add('公司名字：50长度，数字、字母、汉字、下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if (empty($params['id'])) {
            if (preg_match("/^\w{1,20}$/", trim($params['applets_id'])) == false) {
                Err::add('小程序原始id：20长度，数字、字母、下划线', RespCode::PARAMS_ERR);
                return false;
            }
            if (preg_match("/^.{1,20}$/", trim($params['appid'])) == false) {
                Err::add('小程序appid：20长度，数字、字母', RespCode::PARAMS_ERR);
                return false;
            }
            if (preg_match("/^.{1,60}$/", trim($params['secret'])) == false) {
                Err::add('小程序secret：60长度，数字、字母', RespCode::PARAMS_ERR);
                return false;
            }
            if (preg_match("/^.{1,20}$/", trim($params['wechat_appid'])) == false) {
                Err::add('开放平台appid：20长度，数字、字母', RespCode::PARAMS_ERR);
                return false;
            }
            if (preg_match("/^.{1,60}$/", trim($params['wechat_secret'])) == false) {
                Err::add('开放平台secret：60长度，数字、字母', RespCode::PARAMS_ERR);
                return false;
            }
        }

        $int_options = [
            "options" => [
                "min_range" => 1,
                "max_range" => 2000
            ]
        ];
        if (!filter_var($params['agent_num'], FILTER_VALIDATE_INT, $int_options)) {
            Err::add('允许的最大经纪人人数：数字，大于0小于等于2000', RespCode::PARAMS_ERR);
            return false;
        }

        $exists_name = Db::name("company")
            ->where('deleted', 0)
            ->getByname($params['name']);
        if (empty($params['id'])) {
            if ($exists_name) {
                Err::add('公司名字已经存在', RespCode::PARAMS_ERR);
                return false;
            }
        } else {
            if ($params['name'] != $old['name'] && $exists_name) {
                Err::add('公司名字已经存在', RespCode::PARAMS_ERR);
                return false;
            }
        }

        if (empty($params['id'])) {
            if (CompanyAccount::where('deleted', 0)->where('phone|account', $params['f_phone'])->select()->toArray()) {
                Err::add('该手机号已创建过账号', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (count(explode('-', $params['default_city_code'])) != 2) {
            Err::add('default_city_code参数错误', RespCode::PARAMS_ERR);
            return false;
        }

        $data = [
            'f_name'            => trim($params['f_name']),
            'f_phone'           => isset($params['f_phone']) ? trim($params['f_phone']) : '',
            'name'              => trim($params['name']),
            'logo'              => $params['logo'],
            'app_logo'          => $params['app_logo'],
            'province'          => $params['province_name'],
            'city'              => $params['city_name'],
            'area'              => $params['area_name'],
            'address'           => trim($params['address']),
            'city_code'         => $params['city_code'],
            'default_city_code' => $params['default_city_code'],
            'lat'               => empty($params['lat']) ? 0 : $params['lat'],
            'lng'               => empty($params['lng']) ? 0 : $params['lng'],
            'video'             => empty($params['video']) ? '' : $params['video'],
            'agent_num'         => $params['agent_num'],
            'lave_num'          => $params['agent_num'],
            'applets_code'      => isset($params['applets_code']) ? trim($params['applets_code']) : '',
            'itime'             => time(),
            'utime'             => time(),
            'wechat_appid'      => isset($params['wechat_appid']) ? trim($params['wechat_appid']) : '',
            'wechat_secret'     => isset($params['wechat_secret']) ? trim($params['wechat_secret']) : '',
            'applets_id'        => isset($params['applets_id']) ? trim($params['applets_id']) : '',
            'appid'             => isset($params['appid']) ? trim($params['appid']) : '',
            'secret'            => isset($params['secret']) ? trim($params['secret']) : '',
            'website_url'       => 'https://wx.fpainet.com/',
        ];
        Db::startTrans();
        //添加
        if (empty($params['id'])) {
            $company_id = self::insertGetId($data);
            if (!$company_id) {
                Db::rollback();
                Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                return false;
            }
            $company_account = [
                'company_id'      => $company_id,
                'company_shop_id' => 0,
                'phone'           => $params['f_phone'],
                'password'        => md5(substr($params['f_phone'], 5, 6)),
                'account'         => $params['f_phone'],
                'deleted'         => 0,
                'itime'           => time(),
                'utime'           => time(),
            ];
            $res = CompanyAccount::post($company_account);
            if (!$res) {
                Db::rollback();
                Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                return false;
            }
        } //编辑
        else {
            unset($data['wechat_appid']);
            unset($data['wechat_secret']);
            unset($data['applets_id']);
            unset($data['appid']);
            unset($data['secret']);
            unset($data['applets_code']);
            unset($data['f_phone']);

            $use_num = $old['agent_num'] - $old['lave_num'];
            if ($use_num > $params['agent_num']) {
                Err::add("最大经纪人数不得小于已使用经纪人数：{$use_num}", RespCode::PARAMS_ERR);
                return false;
            }

            $data['lave_num'] = $params['agent_num'] - $use_num;

            //删除oss资源
            self::removeReource('logo', $old, $data);
            self::removeReource('app_logo', $old, $data);
            self::removeReource('video', $old, $data);

            self::where('id', $params['id'])->update($data);

            //该公司下面的门店的默认城市
            $shop_default_city = db("company_shop")
                ->where('company_id',$params['id'])
                ->column('city_code');
            $shop_default_city=array_merge(array_unique($shop_default_city));//门店的所有默认城市code

            $company_city_info = db("company")
                ->where('id',$params['id'])
                ->field('city_code,default_city_code')
                ->find();
            $company_city = explode(',',$company_city_info['city_code']);
            foreach ($shop_default_city as $k1=>$v1){
                if(!in_array($v1,$company_city)){
                    db("company_shop")
                        ->where('city_code',$v1)
                        ->update(['city_code'=>$company_city_info['default_city_code']]);
                }
            }
        }
        Db::commit();
        return true;
    }

    protected static function removeReource($resource, $old, $params) {
        if ($old[$resource] != $params[$resource] && !empty($old[$resource])) {
            $oss = Oss::getInstance();
            $oss->delOneFile($old[$resource]);
        }
    }

    /**
     * 公司列表
     * @param $params
     */
    public static function getList($params) {
        empty($params['page']) ? $page = 1 : $page = $params['page'];
        empty($params['long']) ? $long = 10 : $long = $params['long'];
        if (!empty($params['keyword'])) {
            $map[] = ['name', 'like', '%' . trim($params['keyword']) . '%'];
        }
        $fieldRaw1 = "(" . Db::name('company_agent')
                ->where('deleted', 0)
                ->where('company_id', 'c.id')
                ->fetchSql(true)
                ->count() . ") as agent_num";
        $fieldRaw2 = "(" . Db::name('company_shop')
                ->where('deleted', 0)
                ->where('company_id', 'c.id')
                ->fetchSql(true)
                ->count() . ") as shop_num";
        $map[] = ['deleted', '=', 0];
        $column = ['c.id', 'c.logo', 'c.name', 'c.f_name', 'c.f_phone', 'c.itime'];
        $order = ['c.id' => 'desc'];
        $data = self::list_query($map, $page, $long, $column, $order, $fieldRaw1, $fieldRaw2);
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['itime'] = date('Y-m-d H:i', $v['itime']);
        }
        return $data;
    }

    /**
     * 列表query
     * @param $map
     * @param $page
     * @param $long
     * @param $column
     * @param $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function list_query($map, $page, $long, $column, $order, $fieldRaw1, $fieldRaw2) {
        $count = db("company")
            ->where($map)
            ->count();
        if ($count == 0) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
            return $result;
        } else {
            $data = db("company")
                ->alias('c')
                ->where($map)
                ->page($page, $long)
                ->field($column)
                ->fieldRaw($fieldRaw2)
                ->fieldRaw($fieldRaw1)
                ->order($order)
                ->select();
            $pageNum = ceil($count / $long);
            $result = [
                'page'    => $page,
                'pageNum' => $pageNum,
                'count'   => $count,
                'data'    => $data,
            ];
            return $result;
        }
    }


    /**
     * 获取需要编辑的信息
     * @param $params
     * @return array|bool|\PDOStatement|string|\think\Model|null
     */
    public static function getInfo($params) {
        $map[] = ['id', '=', $params['id']];
        $column = ['id,name,video,province,city,area,city_code,address,agent_num,f_name,f_phone,logo,app_logo,video,agent_num,lave_num,lat,lng,default_city_code'];
        $data = self::getOne($map, $column);
        if (empty($data)) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        } else {
            $use_num = $data['agent_num'] - $data['lave_num'];
            $data['use_agent_num'] = $use_num;
            unset($data['lave_num']);
            return $data;
        }
    }

    /**
     * 获取单个数据
     * @param $map
     * @param $column
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($map, $column) {
        $model = new self();
        return $model->where($map)->field($column)->find();
    }

    /**
     * 删除
     * @param $params
     * @return int
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function del($params) {
        Db::startTrans();
        $data = self::where('id', $params['id'])->where('deleted', 0)->find();
        if (empty($data)) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        }
        //删除公司下面所有账户
        if (CompanyAccount::del($params['id']) === false) {
            Err::add('删除失败', RespCode::PARAMS_ERR);
            Db::rollback();
            return false;
        }
        //删除公司
        if (self::where('id', $params['id'])->update(['deleted' => 1]) === false) {
            Err::add('删除失败', RespCode::PARAMS_ERR);
            Db::rollback();
            return false;
        }
        //删除图片
        $oss = Oss::getInstance();
        if (!empty($data['app_logo'])) $oss->delOneFile($data['app_logo']);
        if (!empty($data['logo'])) $oss->delOneFile($data['logo']);
        if (!empty($data['video'])) $oss->delOneFile($data['video']);
        if (!empty($data['video_cover'])) $oss->delOneFile($data['video_cover']);
        if (!empty($data['applets_code'])) $oss->delOneFile($data['applets_code']);
        if (!empty($data['auto_house_url'])) $oss->delOneFile($data['auto_house_url']);
        Db::commit();
        return true;
    }

}
